package com.jason.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {

	int port;

	public Server(int port) {

		this.port = port;
	}

	private HashMap<String, Class> map = new HashMap();

	public void regist(String interfacename, Class clazz) {

		map.put(interfacename, clazz);

	}

	public void unregist(String interfacename, Class clazz) {

		map.remove(interfacename);

	}

	private void start() throws Exception {
		
		ServerSocket server = new ServerSocket(port);
		  Socket socket ;
		while((socket = server.accept())!=null){
		  new Thread(new MyTask(socket)).start();
		  }
	}

	class MyTask implements Runnable {
		
		Socket socket;

		ObjectInputStream ois;
		
		ObjectOutputStream oos;
		public MyTask(Socket socket) throws Exception {
			this.ois = new ObjectInputStream(socket.getInputStream());
			this.oos = new ObjectOutputStream(socket.getOutputStream());
		}

		@Override
		public void run() {
			
			try {
				
				
				

				Class clazz = (Class) ois.readObject();// oos.writeObject(ICall.class);
				Class iCallclazz=map.get(clazz.getName());
				
				
				//System.out.println(iCallclazz.getName());
				String  methodname = (String) ois.readObject();
				
				//System.out.println(methodname);
				
				Object[] args = (Object[]) ois.readObject();
				
				Method method= iCallclazz.getMethod(methodname);
				Object res=method.invoke(iCallclazz.newInstance(), args);
				
				
				

				oos.writeObject(res);
				oos.flush();
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
	
	public static void main(String[] args) throws Exception {
		Server server=new Server(9999);
		server.regist(ICall.class.getName(), ICallimp.class);
		server.start();
	}

}
